(async function() {
    function randint(x) { return Math.floor(Math.random() * x); }
    function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
    function waitRender() { return new Promise(resolve => requestAnimationFrame(resolve)); }

    // 增强版元素等待函数
    async function waitForElement(selector, timeout = 5000) {
        const start = Date.now();
        while (Date.now() - start < timeout) {
            const element = document.querySelector(selector);
            if (element) return element;
            await sleep(200);
        }
        throw new Error(`元素 "${selector}" 在 ${timeout}ms 内未找到`);
    }

    // 页面结构检查
    async function checkPageStructure() {
        const requiredElements = [
            '.user-exam-page',
            'section.el-container.user-exam-page.is-vertical',
            '.user-exam-queMod-flex'
        ];

        for (const selector of requiredElements) {
            await waitForElement(selector);
        }

        return true;
    }

    async function fillAnswer(queTypeCode, answer) {
        if (['SC', 'MC', 'JQ'].indexOf(queTypeCode) !== -1) {
            const groupClass = queTypeCode === 'MC' ? '.el-checkbox-group' : '.el-radio-group';
            const group = await waitForElement(groupClass);
            for (const choice of answer) {
                await waitRender();
                group.children[+choice].click();
                await waitRender();
            }
        } else if (queTypeCode === 'OFI') {
            const input = await waitForElement('.el-input__inner');
            input.value = answer;
            input.dispatchEvent(new Event('input', { bubbles: true }));
            input.focus();
        }
    }

    async function justDoIt(targetScore) {
        // 检查页面结构
        await checkPageStructure();

        // 从vue对象提取答案
        const examContainer = await waitForElement('section.el-container.user-exam-page.is-vertical');
        let comp, paper;

        try {
            comp = examContainer.__vue__;
            paper = comp.$parent.$data.examPaperInfo.partitions[0];
        } catch (err) {
            throw new Error('无法从Vue实例获取考试数据: ' + err.message);
        }

        // 计算错题列表
        const questions = paper.questions.map((e, i) => ({_: Math.random(), e, i})), wrongList = [];
        questions.sort((x, y) => Math.sign(x._ - y._));

        let curScore = 0, index = 0;
        for (; index < questions.length && curScore < targetScore; index++) {
            curScore += +questions[index].e.score;
        }

        for (; index < questions.length; index++) {
            wrongList.push(questions[index].i);
        }

        // 开始答题
        const menu = await waitForElement('.user-exam-queMod-flex');

        for (index = 0; index < questions.length; index++) {
            menu.children[index].click();
            await sleep(10); // 增加等待时间

            const question = paper.questions[index];
            const shouldAnswerWrong = wrongList.indexOf(index) !== -1;

            try {
                if (question.queTypeCode === 'SC') {
                    const choice = shouldAnswerWrong ?
                        randint(question.options.length) :
                        +question.answer;
                    await fillAnswer(question.queTypeCode, [choice]);
                } else if (question.queTypeCode === 'MC') {
                    const choices = shouldAnswerWrong ?
                        [randint(question.options.length)] :
                        question.answer.split(',').map(e => +e);
                    await fillAnswer(question.queTypeCode, choices);
                } else if (question.queTypeCode === 'JQ') {
                    const choice = question.answer === 'Y' ? 0 : 1;
                    await fillAnswer(question.queTypeCode, shouldAnswerWrong ? [1 - choice] : [choice]);
                } else if (question.queTypeCode === 'OFI') {
                    await fillAnswer(question.queTypeCode, shouldAnswerWrong ? '无' : question.answer);
                }
            } catch (err) {
                console.error(`处理第 ${index+1} 题时出错:`, err);
            }

            await sleep(10); // 题间间隔
        }

        return {
            success: true,
            message: `答题完成，目标分数: ${targetScore}，共回答 ${questions.length} 题`
        };
    }

    try {
        // 等待页面完全加载
        await pageLoadComplete();

        // 设置目标分数
        const targetScore = 80;

        // 执行答题
        return await justDoIt(targetScore);
    } catch (err) {
        console.error('脚本执行失败:', err);
        return {
            success: false,
            error: err.message,
            stack: err.stack
        };
    }

    // 页面加载完成判断
    async function pageLoadComplete() {
        // 等待HTML文档加载完成
        await waitForElement('html');

        // 检查页面是否处于加载状态
        const loadingElements = ['loading', 'spinner', 'progress'];
        for (const loader of loadingElements) {
            // 等待加载元素消失
            await waitForElementDisappear(`[class*="${loader}"]`, 15000);
        }

        // 额外等待确保所有资源加载完成
        await sleep(2000);
    }

    // 等待元素消失
    async function waitForElementDisappear(selector, timeout = 5000) {
        const start = Date.now();
        while (Date.now() - start < timeout) {
            if (!document.querySelector(selector)) return true;
            await sleep(200);
        }
        console.warn(`元素 "${selector}" 未在 ${timeout}ms 内消失`);
        return false;
    }
})();